#include "./http.h"
#include "../rt/work.h"
#include "../utils/log.h"
#include <utility>
#include <hv/requests.h>

using namespace hv;

namespace net::http {

static HttpClient client;

Task<std::string> get(std::string &&url) {

    std::string body = co_await rt::run_async([url2 = std::move(url)]() {

        HttpResponsePtr resp = requests::get(url2.c_str());
        if (resp == nullptr) {
            throw HttpException("http get fail resp == nullptr");
        }
        if (resp->status_code != http_status::HTTP_STATUS_OK) {
            throw HttpException("http get fail code != ok");
        }
        return resp->body;
    });

    co_return body;
}

Task<std::string> post(std::string &&url, std::string &&body) {

    std::string body2 = co_await rt::run_async(
        [url2 = std::move(url), body2 = std::move(body)]() mutable {
            HttpResponsePtr resp = requests::post(url2.c_str(), body2);
            if (resp == nullptr) {
                throw HttpException("http post fail resp == nullptr");
            }
            if (resp->status_code != http_status::HTTP_STATUS_OK) {
                throw HttpException("http post fail code != ok");
            }
            return resp->body;
        });
    co_return body2;
}

} // namespace net::http
